package com.example.customizedgroupmessage;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import com.example.customizedgroupmessage.SMSSendActivity.SMSThread;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.*;
import android.widget.*;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.os.AsyncTask;
import android.provider.MediaStore;

public class MailSendActivity extends Activity implements 
RadioGroup.OnCheckedChangeListener{

	public static final int REQUEST_CODE_SENDCOMPLETION=1111;
	public static final int REQUEST_CODE_MAILSEND=2009;
	public static final int REQUEST_CODE_CONFIGURE=4001;
	DBHelper mHelper;
	SQLiteDatabase db;
	Cursor cursor;
	
	String mail;
	String title;
	String msg;
	String fileName;
	int sendType=0;
	int count = 0;
	int mValue;
	
	ProgressDialog mProgress;
	boolean mQuit;
	MailThread mThread;
	RadioGroup radio;
	//Uri uri=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mail_send_activity);	
		radio = (RadioGroup)findViewById(R.id.radioGroup1);
		radio.setOnCheckedChangeListener(this);

		count = 0;
		mQuit = false;

		//메일 제목
		TextView titleView = (TextView) findViewById(R.id.titleView);
		titleView.setText(MailTemplate.mailTemplate.getTitle());

		// 보낼 메시지
		TextView textMsgView = (TextView) findViewById(R.id.textMsgView);
		//textMsgView.setText(MailTemplate.mailTemplate.getOriginalMsg());
		textMsgView.setText("");
		
		for(int i =0; i < MailTemplate.mailTemplate.analyzedMsg.length ; i++){
			if(MailTemplate.mailTemplate.analyzedMsg[i].equals("#name")){
				Drawable d = getResources().getDrawable(R.drawable.name);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
				SpannableString sText = new SpannableString(MailTemplate.mailTemplate.analyzedMsg[i]);
				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				textMsgView.append(sText);
			}
			else if(MailTemplate.mailTemplate.analyzedMsg[i].equals("#status")){
				Drawable d = getResources().getDrawable(R.drawable.status);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
				SpannableString sText = new SpannableString(MailTemplate.mailTemplate.analyzedMsg[i]);
				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				textMsgView.append(sText);
			}
			else if(MailTemplate.mailTemplate.analyzedMsg[i].equals("#org")){
				Drawable d = getResources().getDrawable(R.drawable.org);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
				SpannableString sText = new SpannableString(MailTemplate.mailTemplate.analyzedMsg[i]);
				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				textMsgView.append(sText);
			}
			else if(MailTemplate.mailTemplate.analyzedMsg[i].equals("#custom")){
				Drawable d = getResources().getDrawable(R.drawable.custom);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
				SpannableString sText = new SpannableString(MailTemplate.mailTemplate.analyzedMsg[i]);
				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				textMsgView.append(sText);
			}
			else{
				textMsgView.append(MailTemplate.mailTemplate.analyzedMsg[i]);
			}
		}

		// 받는 사람
		printReceivers();

		// 전송 버튼
		Button btnMailSend = (Button)findViewById(R.id.btnSend);
		btnMailSend.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
				if(sendType==0){  														
					mValue = 0;
					showDialog(0);
					mThread = new MailThread();
					mThread.start();
				}
				else if(sendType==1){
					mValue = 0;
					sendMailChoosingClient();
					
					if(mValue==count){
						Intent intent = new Intent(getBaseContext(), SendCompletion.class);
						startActivityForResult(intent, REQUEST_CODE_SENDCOMPLETION);
					}
				}
			}
		});
	}
	
	@SuppressWarnings("deprecation")
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0:
			mProgress = new ProgressDialog(this);
			mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgress.setTitle("메일 전송 중");
			mProgress.setMessage("Wait...");
			mProgress.setMax(count);
			mProgress.setCancelable(false);	// Back 버튼으로 닫을 수 없음
			
			mProgress.setButton("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					mQuit = true;
					dismissDialog(0);
				}
			});
			
			return mProgress;
		}
		return null;
	}

	
	Handler mHandler = new Handler() {
		@SuppressWarnings("deprecation")
		public void handleMessage(Message msg) {
			mValue = msg.arg1;
			if (mValue < count) {
				mProgress.setProgress(mValue);
			} else {
				mQuit = true;
				dismissDialog(0);
				Intent intent = new Intent(getBaseContext(), SendCompletion.class);
				startActivityForResult(intent, REQUEST_CODE_SENDCOMPLETION);
			}
		}
	};

	
	class MailThread extends Thread {
		public void run() {

			mHelper = new DBHelper(MailSendActivity.this);
			db = mHelper.getWritableDatabase();
			
			String from=null;
			String password=null;
			cursor = db.rawQuery("SELECT mail, password FROM configure", null);
			while (cursor.moveToNext()) {			
				from=cursor.getString(0);
				password=cursor.getString(1);
			}

			cursor = db.rawQuery("SELECT mail, name, status, organization, groupname, custom FROM mail", null);
			while (cursor.moveToNext()) {
				// 변환할 메타데이터 설정
				MailTemplate.mailTemplate.setName(cursor.getString(1)); // name
				if(cursor.getString(2)!=null){ // status
					MailTemplate.mailTemplate.setStatus(cursor.getString(2));
				}
				if(cursor.getString(3)!=null){ // organization
					MailTemplate.mailTemplate.setOrganization(cursor.getString(3));
				}
				else{ // organ 없을 시 group name 사용
					MailTemplate.mailTemplate.setOrganization(cursor.getString(4));
				}
				if(cursor.getString(5)!=null){ // custom
					MailTemplate.mailTemplate.setCustom(cursor.getString(5));
				}

				mail = cursor.getString(0); // 메일 주소
				title=MailTemplate.mailTemplate.getTitle(); // 제목
				msg = MailTemplate.mailTemplate.translate(); // 변환한 메시지
				Intent intent = getIntent();
				String image = intent.getStringExtra("uri");
				if(image!=null){
					Uri uri=null;
					uri = Uri.parse(image.toString());
					fileName=getPathFromUri(uri);
					
					new SendMail().execute(title, msg, from, mail, from, password, fileName);
					}
				else if(image==null){
					
					new SendMail01().execute(title, msg, from, mail, from, password);
				}
				//Toast.makeText(getBaseContext(), fileName, Toast.LENGTH_SHORT).show(); 
				//new SendMail().execute(title, msg, from, mail, from, password, fileName);
				
				
				mValue++;
				Message msg = mHandler.obtainMessage();
				msg.arg1 = mValue;
				mHandler.sendMessage(msg);
				try { Thread.sleep(500); } catch (InterruptedException e) {;}
			}
			cursor.close();
		}
	}
    
	
	 public String getPathFromUri(Uri uri){
		 Cursor cursor = getContentResolver().query(uri, null, null, null, null );
		 cursor.moveToNext(); 
		 String path = cursor.getString( cursor.getColumnIndex( "_data" ) );
		 cursor.close();
		 return path;

		 }

	
	
	private void sendMailChoosingClient(){
		mHelper = new DBHelper(MailSendActivity.this);
		db = mHelper.getWritableDatabase();

		String from=null;
		String password=null;
		cursor = db.rawQuery("SELECT mail, password FROM configure", null);
		while (cursor.moveToNext()) {			
			from=cursor.getString(0);
			password=cursor.getString(1);
		}
		Uri uri=null;
		Intent intent = getIntent();
		String image = intent.getStringExtra("uri");
		if(image!=null){
			
		uri = Uri.parse(image.toString());
		}
		
		
		cursor = db.rawQuery("SELECT mail, name, status, organization, groupname, custom FROM mail", null);
		while (cursor.moveToNext()) {
			// 변환할 메타데이터 설정
			MailTemplate.mailTemplate.setName(cursor.getString(1)); // name
			if(cursor.getString(2)!=null){ // status
				MailTemplate.mailTemplate.setStatus(cursor.getString(2));
			}
			if(cursor.getString(3)!=null){ // organization
				MailTemplate.mailTemplate.setOrganization(cursor.getString(3));
			}
			else{ // organ 없을 시 group name 사용
				MailTemplate.mailTemplate.setOrganization(cursor.getString(4));
			}
			if(cursor.getString(5)!=null){ // custom
				MailTemplate.mailTemplate.setCustom(cursor.getString(5));
			}

			mail = cursor.getString(0); // 메일 주소
			title=MailTemplate.mailTemplate.getTitle(); // 제목
			msg = MailTemplate.mailTemplate.translate(); // 변환한 메시지
			
  
			// 인텐트 객체를 생성
			Intent email = new Intent(Intent.ACTION_SEND);
			email.putExtra(Intent.EXTRA_EMAIL, new String[]{ mail});
			email.putExtra(Intent.EXTRA_SUBJECT, title);
			email.putExtra(Intent.EXTRA_TEXT, msg);	
			if(uri!=null){
				email.putExtra(Intent.EXTRA_STREAM, uri);
			}
			//need this to prompts email client only
			email.setType("message/rfc822");
			
			// 결과값을 받기 위한 Sub Activity 호출
			startActivityForResult(Intent.createChooser(email, "Choose an Email client :"), REQUEST_CODE_MAILSEND);
		}
		cursor.close();
		mHelper.close();
		//Toast.makeText(getBaseContext(), image.toString(), Toast.LENGTH_SHORT).show(); 
		//mQuit = true;
	}
	// onActivityResult()는 결과를 받는 이벤트 핸들러로,
    // startActivityForResult()로 호출한 액티비티가 종료되었을 때 호출된다.
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if(requestCode == REQUEST_CODE_MAILSEND) // Sub Activity 호출시 사용된 요청 코드
        {
            if(resultCode == RESULT_OK) // Sub Activity의 결과 코드
            {
                mValue++;
            }
        }
    }
	

    
    
	// 라디오 버튼 체크 변동시
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		if(group==radio){
			if (checkedId == R.id.radio0)
			{
				sendType=0;
			} 
			else if (checkedId == R.id.radio1){
				sendType=1;
			}
		}
	}
	

	// 받는 사람 출력
	private void printReceivers(){
		TextView textRecieverView = (TextView) findViewById(R.id.textRecieverView);
		textRecieverView.setText("");

		mHelper = new DBHelper(this);
		db = mHelper.getWritableDatabase();
		SpannableStringBuilder ssb;
		int color = Color.GRAY;
		cursor = db.rawQuery("SELECT name, status, organization, groupname, mail FROM mail", null);

		while (cursor.moveToNext()) {
			textRecieverView.append(cursor.getString(0)); // name

			StringBuffer strBuf = new StringBuffer();
			if(cursor.getString(1)!=null){ // status
				strBuf.append(" "+cursor.getString(1));
			}
			//strBuf.append("(");
			if(cursor.getString(2)!=null){ // organization
				strBuf.append("("+cursor.getString(2)+")  ");
			}
			else{ // organ 없을 시 group name 사용
				strBuf.append("("+cursor.getString(3)+")  ");
			}
			//strBuf.append(" "+cursor.getString(4)+") ");

			ssb = new SpannableStringBuilder(strBuf.toString());
			ssb.setSpan(new ForegroundColorSpan(color), 0, strBuf.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			textRecieverView.append(ssb);
			count++;
		}
		cursor.close();
		mHelper.close();

		TextView textRecieverCount = (TextView) findViewById(R.id.textView2);
		textRecieverCount.setText("받는 사람 (" +count+"명)");
	}


}





class SendMail extends AsyncTask<String, Void, String>
{

	@Override
	protected String doInBackground(String... params) {
		// TODO Auto-generated method stub
		GMailSender sender = new GMailSender(params[4], params[5]); // SUBSTITUTE HERE                    
		try {  
			sender.sendMail(  
					params[0],   //subject.getText().toString(),   
					params[1],           //body.getText().toString(),   
					params[2],          //from.getText().toString(),  
					params[3],           //to
					params[6]); //fileName 
		} catch (Exception e) {  
			Log.e("SendMail", e.getMessage(), e);  
	
		}  

		return null;
	}

}

class SendMail01 extends AsyncTask<String, Void, String>
{

	@Override
	protected String doInBackground(String... params) {
		// TODO Auto-generated method stub
		GMailSender sender = new GMailSender(params[4], params[5]); // SUBSTITUTE HERE                    
		try {  
			sender.sendMail(  
					params[0],   //subject.getText().toString(),   
					params[1],           //body.getText().toString(),   
					params[2],          //from.getText().toString(),  
					params[3]           //to
					); 
		} catch (Exception e) {  
			Log.e("SendMail", e.getMessage(), e);  
	
		}  

		return null;
	}

}